import React, { useEffect, useRef,useState } from 'react'
import useSocket from '../../hook/useSocket'
import { List } from 'antd-mobile'
function Msg () {
  const user_id=1
  const server_id = 200
  const {ws,connect} = useSocket(user_id,server_id)
  const list = localStorage.getItem('list')
  const [newslist,setNewsList] = useState(list ? JSON.parse(list):[])

  const time1=useRef()
  const time2=useRef()
  const heartbeatFn = () =>{
    time1.current=setInterval(()=>{
      ws.send(JSON.stringify({type:'heartbeat'}))
    },3000)
    time2.current=setInterval(()=>{
      const currentTime = Date.now()
      const oldTime = localStorage.getItem('heartbeat')
      if(currentTime-oldTime>10000){
        console.log('连接断开，尝试重连')
        ws.close()
        connect()
      }
    },5000)
    
  }

  useEffect(()=>{
    if(ws){
      ws.onopen=()=>{
        console.log('连接成功')
        heartbeatFn()
      }
      ws.onmessage=(e)=>{
        console.log(e.data)
        const {type,data} = JSON.parse(e.data)
        if(type==='heartbeat'){
          localStorage.setItem('heartbeat',Date.now())
        }
        else if(type=='news'){
          setNewsList((list)=>{
            const nstate = [...list,...data]
            localStorage.setItem('list',JSON.stringify(data))
            return nstate
          })
          
        }
      }
      
    }
  },[ws])
  useEffect(()=>{
    return ()=>{
      clearInterval(time1.current)
      clearInterval(time2.current)
    }
  },[])
  return (
    <div>
      <List>
        {
          newslist.map((item,index)=>(
            <List.Item key={index}>
              {item.content}
              {/* <List.Item.Meta
                title={item.title}
                description={item.description}
              /> */}
            </List.Item>
          ))
        }
      </List>
    </div>
  )
}

export default Msg
